import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

/**
 * 应用状态管理
 */
export const useAppStore = defineStore('app', () => {
    // 基础状态
    const isDarkMode = ref<boolean>(true)
    const deviceType = ref<'mobile' | 'tablet' | 'desktop'>('desktop')
    
    // 计算属性
    const isMobile = computed(() => deviceType.value === 'mobile')
    const isTablet = computed(() => deviceType.value === 'tablet')
    const isDesktop = computed(() => deviceType.value === 'desktop')
    
    /**
     * 切换主题模式
     */
    const toggleTheme = (): void => {
        isDarkMode.value = !isDarkMode.value
        updateThemeClass()
        saveThemeToStorage()
    }
    
    /**
     * 设置主题模式
     */
    const setTheme = (dark: boolean): void => {
        isDarkMode.value = dark
        updateThemeClass()
        saveThemeToStorage()
    }
    
    /**
     * 更新主题类名
     */
    const updateThemeClass = (): void => {
        const html = document.documentElement
        if (isDarkMode.value) {
            html.classList.add('dark')
        } else {
            html.classList.remove('dark')
        }
    }
    
    /**
     * 检测设备类型
     */
    const detectDevice = (): void => {
        const width = window.innerWidth
        if (width < 768) {
            deviceType.value = 'mobile'
        } else if (width < 1024) {
            deviceType.value = 'tablet'
        } else {
            deviceType.value = 'desktop'
        }
    }
    
    /**
     * 处理窗口大小变化
     */
    const handleResize = (): void => {
        detectDevice()
    }
    
    /**
     * 处理在线状态变化
     */
    const handleOnlineStatusChange = (): void => {
        // 可以在这里添加在线状态变化的处理逻辑
        console.log('网络状态变化:', navigator.onLine ? '在线' : '离线')
    }
    
    /**
     * 初始化应用
     */
    const initializeApp = (): void => {
        // 从本地存储恢复主题设置
        loadThemeFromStorage()
        
        // 应用主题
        updateThemeClass()
        
        // 检测设备类型
        detectDevice()
    }
    
    /**
     * 保存主题设置到本地存储
     */
    const saveThemeToStorage = (): void => {
        try {
            localStorage.setItem('theme_mode', isDarkMode.value ? 'dark' : 'light')
        } catch (error) {
            console.error('保存主题设置失败:', error)
        }
    }
    
    /**
     * 从本地存储加载主题设置
     */
    const loadThemeFromStorage = (): void => {
        try {
            const savedTheme = localStorage.getItem('theme_mode')
            if (savedTheme) {
                isDarkMode.value = savedTheme === 'dark'
            }
        } catch (error) {
            console.error('加载主题设置失败:', error)
        }
    }
    
    return {
        // 状态
        isDarkMode,
        deviceType,
        
        // 计算属性
        isMobile,
        isTablet,
        isDesktop,
        
        // 方法
        toggleTheme,
        setTheme,
        detectDevice,
        handleResize,
        handleOnlineStatusChange,
        initializeApp
    }
})